package com.huike.clues.service.impl;

import com.github.pagehelper.PageHelper;
import com.huike.clues.mapper.SysDeptMapper;
import com.huike.clues.mapper.SysRoleMapper;
import com.huike.clues.service.ISysDeptService;
import com.huike.common.constant.UserConstants;
import com.huike.common.core.domain.TreeDeptAndUser;
import com.huike.common.core.domain.TreeSelect;
import com.huike.common.core.domain.entity.SysDeptDTO;
import com.huike.common.core.domain.entity.SysRoleDTO;
import com.huike.common.exception.CustomException;
import com.huike.common.utils.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;

import static net.bytebuddy.matcher.ElementMatchers.hasChild;

@Service
public class SysDeptServiceImpl implements ISysDeptService {
    @Resource
    private SysDeptMapper deptMapper;
    @Resource
    private SysRoleMapper roleMapper;
    /**
     * 构建前端所需要树结构
     *
     * @param depts 部门列表
     * @return 树结构列表
     */
    @Override
    public List<SysDeptDTO> buildDeptTree(List<SysDeptDTO> depts)
    {
        List<SysDeptDTO> returnList = new ArrayList<SysDeptDTO>();
        List<Long> tempList = new ArrayList<Long>();
        for (SysDeptDTO dept : depts)
        {
            tempList.add(dept.getDeptId());
        }
        for (Iterator<SysDeptDTO> iterator = depts.iterator(); iterator.hasNext();)
        {
            SysDeptDTO dept = (SysDeptDTO) iterator.next();
            // 如果是顶级节点, 遍历该父节点的所有子节点
            if (!tempList.contains(dept.getParentId()))
            {
                recursionFn(depts, dept);
                returnList.add(dept);
            }
        }
        if (returnList.isEmpty())
        {
            returnList = depts;
        }
        return returnList;
    }
    /**
     * 递归列表
     */
    private void recursionFn(List<SysDeptDTO> list, SysDeptDTO t)
    {
        // 得到子节点列表
        List<SysDeptDTO> childList = getChildList(list, t);
        t.setChildren(childList);
        for (SysDeptDTO tChild : childList)
        {
            if (hasChild(list, tChild))
            {
                recursionFn(list, tChild);
            }
        }
    }
    /**
     * 得到子节点列表
     */
    private List<SysDeptDTO> getChildList(List<SysDeptDTO> list, SysDeptDTO t)
    {
        List<SysDeptDTO> tlist = new ArrayList<SysDeptDTO>();
        Iterator<SysDeptDTO> it = list.iterator();
        while (it.hasNext())
        {
            SysDeptDTO n = (SysDeptDTO) it.next();
            if (StringUtils.isNotNull(n.getParentId()) && n.getParentId().longValue() == t.getDeptId().longValue())
            {
                tlist.add(n);
            }
        }
        return tlist;
    }

    /**
     * 判断是否有子节点
     */
    private boolean hasChild(List<SysDeptDTO> list, SysDeptDTO t)
    {
        return getChildList(list, t).size() > 0 ? true : false;
    }

    @Override
    public List<SysDeptDTO> selectDeptList(SysDeptDTO dept) {
        return deptMapper.selectDeptList(dept);
    }
    @Override
    public SysDeptDTO selectDeptById(Long deptId) {
        return deptMapper.selectDeptById(deptId);
    }

    @Override
    public List<TreeSelect> buildDeptTreeSelect(List<SysDeptDTO> depts) {
        List<SysDeptDTO> deptTrees = buildDeptTree(depts);
        return deptTrees.stream().map(TreeSelect::new).collect(Collectors.toList());
    }

    @Override
    public List<TreeSelect> buildDeptAndUserTree(List<SysDeptDTO> depts){
        List<SysDeptDTO> deptTrees = buildDeptTree(depts);
        return deptTrees.stream().map(TreeDeptAndUser::new).collect(Collectors.toList());
    }

    /**
     * 根据角色ID查询部门树信息
     *
     * @param roleId 角色ID
     * @return 选中部门列表
     */
    @Override
    public List<Integer> selectDeptListByRoleId(Long roleId)
    {
        SysRoleDTO role = roleMapper.selectRoleById(roleId);
        return deptMapper.selectDeptListByRoleId(roleId, role.isDeptCheckStrictly());
    }

    @Override
    public String checkDeptNameUnique(SysDeptDTO dept) {
        Long deptId = StringUtils.isNull(dept.getDeptId()) ? -1L : dept.getDeptId();
        SysDeptDTO info = deptMapper.checkDeptNameUnique(dept.getDeptName(), dept.getParentId());
        if (StringUtils.isNotNull(info) && info.getDeptId().longValue() != deptId.longValue())
        {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    @Override
    public int insertDept(SysDeptDTO dept) {
        SysDeptDTO info = deptMapper.selectDeptById(dept.getParentId());
        dept.setAncestors(info.getAncestors() + "," + dept.getParentId());
        return deptMapper.insertDept(dept);
    }

    @Override
    public int selectNormalChildrenDeptById(Long deptId) {
        return deptMapper.selectNormalChildrenDeptById(deptId);
    }

    @Override
    public int updateDept(SysDeptDTO dept) {
        SysDeptDTO newParentDept = deptMapper.selectDeptById(dept.getParentId());
        SysDeptDTO oldDept = deptMapper.selectDeptById(dept.getDeptId());
        if (StringUtils.isNotNull(newParentDept) && StringUtils.isNotNull(oldDept)){
            String newAncestors = newParentDept.getAncestors() + "," + newParentDept.getDeptId();
            String oldAncestors = oldDept.getAncestors();
            dept.setAncestors(newAncestors);
            updateDeptChildren(dept.getDeptId(),newAncestors,oldAncestors);
        }
        int result = deptMapper.updateDept(dept);
        if (UserConstants.DEPT_NORMAL.equals(dept.getStatus())){
            //如果该部门是启用状态,则启用该部门的所有上级
            updateParentDeptStatus(dept);
        }
        return result;
    }

    @Override
    public boolean hasChildByDeptId(Long deptId) {
        int result = deptMapper.hasChildByDeptId(deptId);
        return result > 0 ? true : false;
    }

    @Override
    public boolean checkDeptExistUser(Long deptId) {
        int result = deptMapper.checkDeptExistUser(deptId);
        return result > 0 ? true : false;
    }

    @Override
    public int deleteDeptById(Long deptId) {
        return deptMapper.deleteDeptById(deptId);
    }

    @Override
    public List<SysDeptDTO> selectDeptAndUserList() {
        return deptMapper.selectDeptAndUserList();
    }

    /**
     * 修改该部门的父级部门状态
     *
     * @param dept 当前部门
     */
    private void updateParentDeptStatus(SysDeptDTO dept)
    {
        String updateBy = dept.getUpdateBy();
        dept = deptMapper.selectDeptById(dept.getDeptId());
        dept.setUpdateBy(updateBy);
        deptMapper.updateDeptStatus(dept);
    }

    /**
     * 修改子元素关系
     *
     * @param deptId 被修改的部门ID
     * @param newAncestors 新的父ID集合
     * @param oldAncestors 旧的父ID集合
     */
    public void updateDeptChildren(Long deptId, String newAncestors, String oldAncestors)
    {
        List<SysDeptDTO> children = deptMapper.selectChildrenDeptById(deptId);
        for (SysDeptDTO child : children)
        {
            child.setAncestors(child.getAncestors().replace(oldAncestors, newAncestors));
        }
        if (children.size() > 0)
        {
            deptMapper.updateDeptChildren(children);
        }
    }
}
